/*
 * 优惠券管理
 * @date 2016/5/4
 */

//列表每页显示条数
var perPage = 10;

//是否请求完成标识
var loadBool = true;

// 页面初始化
$(function () {
    getStartCity($("#startCities"), $("#endCities"), $(this));
    list();
});

// 查询优惠券
$('#query').click(function () {
    list();
});

// 清空
$(document).delegate("#clear", "click", function () {
    $("#startCities").val('');
    $("#startCities").attr('data', '');
    $("#endCities").val('');
    $("#endCities").attr('data', '');
    $("#name").val('');
    $("#whenexpire").val('-1');
    $("#type").val('-1');
    $("#business").val('-1');
    $("#list").empty();
    list();
});

function list() {
    $("#curPage").text(0);
    $("#pages").text(0);
    getCouponList(1);
}

//下一页
$(document).delegate("#nextPage", "click", function () {
    var curPage = Number($("#curPage").text());
    var pages = Number($("#pages").text());
    if (curPage == pages) {
        return;
    }
    getCouponList(curPage + 1);
});

//上一页
$(document).delegate("#lastPage", "click", function () {
    var curPage = Number($("#curPage").text());
    if (curPage <= 1) {
        return;
    }
    getCouponList(curPage - 1);
});

// 添加优惠券
$('#add,.table .modify').click(function () {
    var index = layer.open({
        type: 2,
        title: false,
        closeBtn: 0, //不显示关闭按钮
        maxmin: false,
        content: '/couponadd/cadd',
        success: function (layero, index) {
            initAddCoupon(layero, index);
        }
    });
    layer.full(index);
});

// 点击修改优惠券
$(".table").delegate("a.modify", "click", function () {
    if ($(this).hasClass("invalid")) {
        return;
    }
    var id = $(this).parent().siblings('#id').text();
    var index = layer.open({
        type: 2,
        title: false,
        closeBtn: 0, //不显示关闭按钮
        maxmin: false,
        content: '/couponmodify/cmodify',
        success: function (layero, index) {
            initModifyCoupon(layero, id);
        }
    });
    layer.full(index);
});

//点击删除优惠券
$(".table").delegate("a.del", "click", function () {
    if ($(this).hasClass("invalid")) {
        return;
    }
    var id = $(this).parent().siblings('#id').text();
    layer.confirm('确定删除该优惠券？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        var param = JSON.stringify({"id": id});
        $.ajax({
            type: "POST",
            url: "/couponmanager/del",
            contentType: "application/json",
            dataType: "json",
            data: param,
            success: function (data) {
                if (data.status == 0) {
                    layer.msg('已删除', {icon: 1, time: 1000/*1秒后自动关闭*/});
                    list();
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                bbx_alert_error("出错啦~");
            }
        });
    });
});

// 返回上一页
function back(elem) {
    elem.on('click', "#back", function () {
        is_incity = -1;
        layer.closeAll();
    });
}

// 标记业务分类
function bussinessMark(elem) {
    elem.on('click', "input[type='checkbox']", function () {
        var bussiness = '';
        if (elem.find("#city").prop("checked")) {
            if (elem.find("#busAll").prop("checked") || elem.find("#citypin").prop("checked") || elem.find("#citybao").prop("checked") || elem.find("#package").prop("checked")) {
                is_incity = -1;//城际和市内
            } else {
                is_incity = 1;//市内
                bussiness = '市内';
            }
        } else {
            is_incity = 0;//城际
            bussiness = '城际';
        }
        if (is_incity != -1) {
            elem.find('.route-part-control .line-model').each(function () {
                var start = $(this).find('input:first-child').val();
                if (start.indexOf(bussiness) == -1) {
                    $(this).find('input:first-child').val('');
                    $(this).find('input:nth-child(2)').val('');
                }
            });
        }
    });
}

//生成优惠券数据
function generateCouponData(data) {
    var type = '', time = '', sum = '', business = '', line = '', paymode = '', use = '';
    switch (data.data.type) {//优惠券类型和金额
        case 0:
            type = "抵用券";
            sum = data.data.sum + "元";
            break;
        case 1:
            type = "折扣券";
            var discount = data.data.discount % 10 ? data.data.discount : data.data.discount / 10;
            sum = discount + "折";
            break;
        case 2:
            type = "体验券";
            sum = data.data.sum + "元";
            break;
    }
    switch (data.data.whenexpire) {//有效期
        case 0:
            time = "长期有效";
            break;
        case 1:
            time = "领取后" + data.data.expirein + "小时";
            break;
        case 2:
            time = data.data.expiretime;
            break;
    }
    if (data.useconditions) {
        if (data.useconditions.business) {
            var lineType = '全部';//路线类型，0：全部，1：全部城际，2：全部市内
            var busi = data.useconditions.business; //业务
            if (busi == -1) {
                business = "全部";
            } else {
                var busiArray = new Array(0, 0, 0, 0);
                for (var i = 3; i >= 0; i--) {
                    var j = parseInt(busi / (Math.pow(2, i)));
                    if (j > 0) {
                        busiArray[i] = 1;
                    }
                    busi %= (Math.pow(2, i));
                    if (busi == 0) {
                        break;
                    }
                }
                business += busiArray[0] ? "城际拼车<br>" : '';
                business += busiArray[1] ? "城际包车<br>" : '';
                business += busiArray[2] ? "小件快递<br>" : '';
                business += busiArray[3] ? "市内打车<br>" : '';
                if (busiArray[3]) {
                    if (!busiArray[0] && !busiArray[1] && !busiArray[2]) {
                        lineType = '全部市内';
                    }
                } else {
                    lineType = '全部城际';
                }
            }
        }
        if (data.useconditions.line) {
            for (var i = 0; i < data.useconditions.line.length; i++) {//路线
                if (data.useconditions.line[i] == "*") {
                    line = lineType;
                    break;
                }
                line += data.useconditions.line[i].line_name + '<br>';
            }
        }
        switch (data.useconditions.paymode) {//支付方式
            case 1:
                paymode = "仅线上可用";
                break;
            case 2:
                paymode = "仅线下可用";
                break;
            case 3:
                paymode = "不限";
                break;
        }
        use = data.useconditions.sum_low_limit && data.useconditions.sum_low_limit > 0 ? "满" + data.useconditions.sum_low_limit + "可用" : "无限制";//使用限制
    }
    var opt = ''; //操作
    if (data.refcnt > 0) {
        opt = "<a class=\"del invalid\" href=\"javascript:void(0);\" title=\"\">删除</a>  <a class=\"modify invalid\" href=\"javascript:void(0);\" title=\"\">修改</a>";
    } else {
        opt = "<a class=\"del\" href=\"javascript:void(0);\" title=\"\">删除</a>  <a class=\"modify\" href=\"javascript:void(0);\" title=\"\">修改</a>";
    }
    var coupon = {
        id: data.id,
        friendlyid: data.friendlyid,
        name: data.name,
        type: type,
        time: time,
        sum: sum,
        business: business,
        line: line,
        paymode: paymode,
        use: use,
        option: opt
    };
    return coupon;
}

//获取优惠券列表
function getCouponList(curPage) {
    if (!loadBool) {
        return;
    }
    loadBool = false;
    $("#list").empty();
    //loading层
    var layerIndex = layer.load(2, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });

    var index = curPage - 1;
    var params = JSON.stringify({
        "whenexpire": Number($("#whenexpire option:selected").val()),
        "line": $("#startCities").attr('data') && $("#endCities").attr('data') ? $("#startCities").attr('data') + '_to_' + $("#endCities").attr('data') : '',
        "type": Number($("#type option:selected").val()),
        "business": Number($("#business option:selected").val()),
        "pattern": $("#name").val(),
        'pos': index * perPage,
        'limit': perPage
    });
    $.ajax({
        type: "POST",
        url: "/couponmanager/glist",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            layer.close(layerIndex);
            if (data.status == 0) {
                $("#pages").text(Math.ceil(data.count / perPage));
                if (data.data.length > 0) {
                    $("#curPage").text(index + 1);
                    for (var i = 0; i < data.data.length; i++) {
                        var coupon = generateCouponData(data.data[i]);
//                        var startCity = $('#startCities').val();
//                        if(startCity) {
//                            var cityType = startCity.indexOf('城际') != -1 ? '城际':'市内';
//                            if(coupon.line.indexOf('全部') != -1) {
//                                if(coupon.line.indexOf(cityType) == -1) {
//                                    continue;
//                                }
//                            }
//                        }
                        var row = "<tr>" +
                                "<td id='id' style='display:none'>" + coupon.id + "</td>" +
                                "<td>" + coupon.friendlyid + "</td>" +
                                "<td>" + coupon.name + "</td>" +
                                "<td>" + coupon.type + "</td>" +
                                "<td>" + coupon.time + "</td>" +
                                "<td>" + coupon.sum + "</td>" +
                                "<td>" + coupon.business + "</td>" +
                                "<td>" + coupon.line + "</td>" +
                                "<td>" + coupon.paymode + "</td>" +
                                "<td>" + coupon.use + "</td>" +
                                "<td>" + coupon.option + "</td>" +
                                "</tr>";
                        $("#list").append(row);
                    }
                }
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
            loadBool = true;
        },
        error: function () {
            layer.close(layerIndex);
            bbx_alert_error("出错啦~");
            loadBool = true;
        }
    });
}

/*
 * 添加优惠券
 * @date 2016/5/5
 */

function initAddCoupon(layero, index) {
    var layerIframe = layero.find('iframe:first-child').contents();
    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
    addLinesModel(layerIframe);
    bussinessMark(layerIframe);
    back(layerIframe);
    layerIframe.find("#add").on("click", function () {
        if (!checkParam(layerIframe)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var params = createParam(layerIframe);
        var layerIndex = layer.msg('新增中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/couponmanager/add",
            contentType: "application/json",
            dataType: "json",
            data: params,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                        is_incity = -1;
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error("出错啦~");
            }
        });
    });
}

//检查参数
function checkParam(layerIframe) {
    var rightParam = true;
    layerIframe.find("#name").val() ? layerIframe.find("#namemark").text('') : (layerIframe.find("#namemark").text('请填写！'), rightParam = false);
    switch (layerIframe.find("#type option:selected").val()) {
        case "0":
        case "2":
            layerIframe.find("#sum").val() ? layerIframe.find("#summark").text('') : (layerIframe.find("#summark").text('请填写!'), rightParam = false);
            break;
        case "1":
            layerIframe.find("#discount").val() ? layerIframe.find("#discountmark").text('') : (layerIframe.find("#discountmark").text('请填写!'), rightParam = false);
            break;
    }
    switch (layerIframe.find("#whenexpire option:selected").val()) {
        case "1":
            layerIframe.find("#expirein").val() ? layerIframe.find("#expireinmark").text('') : (layerIframe.find("#expireinmark").text('请填写!'), rightParam = false);
            break;
        case "2":
            layerIframe.find("#expiretime").val() ? layerIframe.find("#expiretimemark").text('') : (layerIframe.find("#expiretimemark").text('请填写！'), rightParam = false);
            break;
    }
    var allBusinessNotChecked = true;
    layerIframe.find("#business input").each(function () {
        if ($(this).prop("checked")) {
            allBusinessNotChecked = false;
        }
    });
    allBusinessNotChecked ? (layerIframe.find("#businessmark").text('请选择业务类型！'), rightParam = false) : layerIframe.find("#businessmark").text('');
    if (layerIframe.find("#routePart").attr("checked")) {
        var allRouteRight = true;
        layerIframe.find('.route-part-control .line-model').each(function () {
            if (!$(this).find('input:first-child').attr('data') || !$(this).find('input:nth-child(2)').attr('data')) {
                allRouteRight = false;
            }
        });
        allRouteRight ? layerIframe.find("#routePartmark").text('') : (layerIframe.find("#routePartmark").text('请选择线路！'), rightParam = false);
    }
    switch (layerIframe.find("#limitSelect option:selected").val()) {
        case "0":
            layerIframe.find("#usesum").val() ? layerIframe.find("#usesummark").text('') : (layerIframe.find("#usesummark").text('请填写!'), rightParam = false);
            break;
    }
    return rightParam;
}

//构造参数
function createParam(layerIframe, id) {
    var business = 0;
    if (layerIframe.find("#busAll").prop("checked")) {
        business = -1;
    } else {
        layerIframe.find("#business input:checked").each(function () {
            business += parseInt($(this).attr('val'));
        });
    }

    var params = JSON.stringify({
        'id': id ? id : '',
        'name': layerIframe.find("#name").val(),
        'type': Number(layerIframe.find("#type option:selected").val()),
        'sum': Number(layerIframe.find("#sum").val()),
        'discount': layerIframe.find("#discount").val().length == 1 ? Number(layerIframe.find("#discount").val()) * 10 : Number(layerIframe.find("#discount").val()),
        'whenexpire': Number(layerIframe.find("#whenexpire option:selected").val()),
        'expirein': Number(layerIframe.find("#expirein").val()),
        'expiretime': layerIframe.find("#expiretime").val(),
        'line': routeSelect(layerIframe),
        'business': business,
        'sum_low_limit': layerIframe.find("#usesum").val() ? Number(layerIframe.find("#usesum").val()) : -1,
        'paymode': Number(layerIframe.find("#paymode input:checked").attr('val'))
    });
    console.log(params);
    return params;
}

//修改优惠券
function initModifyCoupon(layero, id) {
    var layerIframe = layero.find('iframe:first-child').contents();
    addLinesModel(layerIframe);
    bussinessMark(layerIframe);
    back(layerIframe);
    fillDetailInfo(layerIframe, id);
    modify(layerIframe, id);
}

//填充详情
function fillDetailInfo(layerIframe, id) {
//    if (!loadBool) {
//        return;
//    }
//    loadBool = false;
    $.ajax({
        type: "POST",
        url: "/couponmanager/ginfo",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"id": id}),
        success: function (data) {
            if (data.status == 0) {
                _fillDetailInfo(layerIframe, data);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
//            loadBool = true;
        },
        error: function () {
            bbx_alert_error("出错啦~");
//            loadBool = true;
        }
    });
}

function _fillDetailInfo(layerIframe, data) {
    layerIframe.find("#name").val(data.name);//名称
    switch (data.data.type) {//类型和金额
        case 0:
            layerIframe.find("#type option[value='0']").attr("selected", true);
            layerIframe.find("#sum").val(data.data.sum);
            layerIframe.find('.form-sum').show();
            break;
        case 1:
            layerIframe.find("#type option[value='1']").attr("selected", true);
            var discount = data.data.discount % 10 ? data.data.discount : data.data.discount / 10;
            layerIframe.find("#discount").val(discount);
            layerIframe.find('.form-discount').show();
            break;
        case 2:
            layerIframe.find("#type option[value='2']").attr("selected", true);
            layerIframe.find("#sum").val(data.data.sum);
            layerIframe.find('.form-sum').show();
            break;
    }
    switch (data.data.whenexpire) {//有效期
        case 0:
            layerIframe.find("#whenexpire option[value='0']").attr("selected", true);
            break;
        case 1:
            layerIframe.find("#whenexpire option[value='1']").attr("selected", true);
            layerIframe.find("#expirein").val(data.data.expirein);
            layerIframe.find("#expireincss").show();
            break;
        case 2:
            layerIframe.find("#whenexpire option[value='2']").attr("selected", true);
            layerIframe.find("#expiretime").val(data.data.expiretime);
            layerIframe.find("#expiretimecss").show();
            break;
    }
    if (data.useconditions) {
        if (data.useconditions.business) {
            var busi = data.useconditions.business; //业务
            if (busi == -1) {
                layerIframe.find("input[type='checkbox']").prop("checked", true);
            } else {
                var busiArray = new Array(0, 0, 0, 0);
                for (var i = 3; i >= 0; i--) {
                    var j = parseInt(busi / (Math.pow(2, i)));
                    if (j > 0) {
                        busiArray[i] = 1;
                    }
                    busi %= (Math.pow(2, i));
                    if (busi == 0) {
                        break;
                    }
                }
                if (busiArray[0]) {
                    layerIframe.find("#citypin").prop("checked", true);
                }
                if (busiArray[1]) {
                    layerIframe.find("#citybao").prop("checked", true);
                }
                if (busiArray[2]) {
                    layerIframe.find("#package").prop("checked", true);
                }
                if (busiArray[3]) {
                    layerIframe.find("#city").prop("checked", true);
                    if (!busiArray[0] && !busiArray[1] && !busiArray[2]) {
                        is_incity = 1;
                    }
                } else {
                    is_incity = 0;
                }
            }
        }
        if (data.useconditions.line) {
            for (var i = 0; i < data.useconditions.line.length; i++) {//路线
                if (data.useconditions.line[i] == "*") {
                    layerIframe.find("#routeAll").attr("checked", true);
                    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
                    break;
                }
                var line = data.useconditions.line[i].line_id.split("_to_");
                if (i == 0) {
                    layerIframe.find("#routePart").attr("checked", true);
                    layerIframe.find("#routePartcss").removeClass('display-none');
                    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe, line[0], line[1]);
                } else {
                    _addLinesModel(layerIframe.find('.line-buttons .increase'), layerIframe, true, line[0], line[1]);
                }
            }
        } else {
            getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
        }
        switch (data.useconditions.paymode) {//支付方式
            case 1:
                layerIframe.find("#payonline").attr("checked", true);
                break;
            case 2:
                break;
            case 3:
                layerIframe.find("#payall").attr("checked", true);
                break;
        }
        !data.useconditions.sum_low_limit || data.useconditions.sum_low_limit < 0 ?
                layerIframe.find("#limitSelect option[value='-1']").attr("selected", true) :
                (layerIframe.find("#limitSelect option[value='0']").attr("selected", true),
                        layerIframe.find("#usesum").val(data.useconditions.sum_low_limit),
                        layerIframe.find("#usesumcss").show());
    }
}

//确认修改
function modify(layerIframe, id) {
//    if (!loadBool) {
//        return;
//    }
//    loadBool = false;
    layerIframe.find("#modify").on("click", function () {
        if (!checkParam(layerIframe)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var params = createParam(layerIframe, id);
        var layerIndex = layer.msg('修改中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/couponmanager/modify",
            contentType: "application/json",
            dataType: "json",
            data: params,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('修改成功！', {icon: 1, time: 1000}, function () {
                        is_incity = -1;
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
//                loadBool = true;
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error("出错啦~");
//                loadBool = true;
            }
        });
    });
}
